package com.kunpeng.weibo.renren.api;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.kunpeng.weibo.renren.utils.Invoker;

/**
 * 
 * @author DuYang (yang.du@renren-inc.com) 2011-12-14
 * 
 */
public abstract class Base_API {
	protected Invoker	invoker;

	public Base_API(Invoker invoker) {
		this.invoker = invoker;
	}

	protected String getResultValue(TreeMap<String, String> params, String propertyName) {
		String ret = this.invoker.sendPostRestRequest(params);
		//        JSONObject obj = (JSONObject) JSONValue.parse(ret);
		JSONObject obj;
		try {
			obj = new JSONObject(ret);
			Object o = obj.get(propertyName);
			if (o == null)
				return "";
			return o.toString();
		} catch (JSONException e) {
			e.printStackTrace();
			return "";
		}

	}

	protected int getResultInt(TreeMap<String, String> params) {
		String str = this.getResultValue(params, "result");
		return Integer.parseInt(str.trim());
	}

	protected int getResultInt(TreeMap<String, String> params, String key) {
		String str = this.getResultValue(params, key);
		return Integer.parseInt(str.trim());
	}

	protected boolean getResultBoolean(TreeMap<String, String> params) {
		int r = this.getResultInt(params);
		if (r == 1) {
			return true;
		}
		return false;
	}

	protected JSONObject getResultJSONObject(TreeMap<String, String> params) {
		String ret = this.invoker.sendPostRestRequest(params);
		//        return (JSONObject) JSONValue.parse(ret);
		try {
			return new JSONObject(ret);
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}

	protected JSONArray getResultJSONArray(TreeMap<String, String> params) {
		String ret = this.invoker.sendPostRestRequest(params);
		//        return (JSONArray) JSONValue.parse(ret);
		try {
			return new JSONArray(ret);
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}

	protected List<Integer> getResultIntList(TreeMap<String, String> params) {
		JSONArray array = this.getResultJSONArray(params);
		List<Integer> ints = new ArrayList<Integer>();
		for (int i = 0; i < array.length(); i++) {
			try {
				Object obj = array.get(i);
				if (obj != null) {
					ints.add(Integer.parseInt(obj.toString()));
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return ints;
	}

	protected List<String> getResultStringList(TreeMap<String, String> params) {
		JSONArray array = this.getResultJSONArray(params);
		List<String> strs = new ArrayList<String>();
		for (int i = 0; i < array.length(); i++) {
			try {
				Object obj = array.get(i);
				if (obj != null) {
					strs.add(array.get(i).toString());
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return strs;
	}
}
